package org.jeecg.modules.act.wx;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jdk.nashorn.internal.objects.ArrayBufferView;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.wx.BASE64DecodedMultipartFile;
import org.jeecg.common.wx.Const;
import org.jeecg.common.wx.NetUtil;
import org.jeecg.common.wx.UploadUtil;
import org.jeecg.modules.act.dto.ActDictDto;
import org.jeecg.modules.act.dto.ActMsgDto;
import org.jeecg.modules.act.dto.Verify;
import org.jeecg.modules.act.dto.WxAct;
import org.jeecg.modules.act.entity.ActDict;
import org.jeecg.modules.act.entity.ActMsg;
import org.jeecg.modules.act.service.IActDictService;
import org.jeecg.modules.act.service.IActMsgService;
import org.jeecg.modules.act.service.IActShareService;
import org.jeecg.modules.act.service.IActivityService;
import org.jeecg.modules.act.vo.ActDictVo;
import org.jeecg.modules.act.vo.ActQr;
import org.jeecg.modules.act.vo.ActivityVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;


import javax.annotation.Resource;
import javax.imageio.stream.FileImageOutputStream;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.*;


/**
 * 管理相关的controller
 */
@RestController
@RequestMapping("/wx/")
@Api(tags = "wx_管理报名接口")
@Slf4j
public class MangerController {

    @Autowired
    private IActivityService activityService;
    @Autowired
    private IActDictService dictService;
    @Autowired
    private IActMsgService msgService;
    @Autowired
    private IActShareService shareService;

    @ApiOperation(value = "审核", notes = "审核报名")
    @PostMapping("verify")
    public Result verify(@RequestBody Verify verify) {
        return activityService.verify(verify);
    }

    @ApiOperation(value = "发布活动", notes = "发布活动")
    @ApiImplicitParam(value = "表单id", name = "formId", required = true)
    @PostMapping("addActivity")
    public Result addActivity(@RequestBody WxAct act) {
        return activityService.addAct(act);
    }

    @ApiOperation("去编辑活动详情页数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "actId", value = "活动id", required = true)
    })
    @GetMapping("goEditActivity")
    public Result goEditActivity(String actId) {
        return activityService.goEditActivity(actId);
    }

    @ApiOperation(value = "修改活动", notes = "修改活动")
    @ApiImplicitParam(value = "活动id", name = "actId")
    @PostMapping("editActivity")
    public Result editActivity(@RequestBody WxAct act, String actId) {
        return activityService.editActivity(act, actId);
    }

    @ApiOperation(value = "添加活动报名须填事项")
    @PostMapping("addDict")
    public Result addDict(@RequestBody ActDictDto dto) {
        return dictService.addDict(dto);
    }

    @ApiOperation(value = "活动须填参数list", notes = "活动须填参数list")
    @GetMapping("dictList")
    public Result<List<ActDictVo>> dictList() {
        Result<List<ActDictVo>> result = new Result<>();
        QueryWrapper<ActDict> wrapper = new QueryWrapper<>(new ActDict());
        wrapper.eq("del_flag", 0);
        wrapper.orderByAsc("create_time");
        List<ActDict> list = dictService.list(wrapper);
        List<ActDictVo> voList = new ArrayList<>();
        list.forEach(l -> {
            ActDictVo vo = new ActDictVo();
            BeanUtils.copyProperties(l, vo);
            voList.add(vo);
        });
//        voList.sort(Comparator.comparingInt(ActDictVo::getSort));
        result.setSuccess(true);
        result.setResult(voList);
        return result;
    }

    @ApiOperation("我管理的活动list")
    @GetMapping("getActList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "页码", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "条数", defaultValue = "10"),
            @ApiImplicitParam(name = "userId", value = "用户id", required = true)
    })
    public Result<IPage<ActivityVo>> actList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                             String userId) {
        Result<IPage<ActivityVo>> result = new Result<>();
        Page<ActivityVo> page = new Page<>(pageNo, pageSize);
        IPage<ActivityVo> pageList = activityService.findByPage(page, userId);
        result.setResult(pageList);
        result.setSuccess(true);
        return result;
    }


    @ApiOperation(value = "添加消息")
    @PostMapping("addMsg")
    public Result addMsg(@RequestBody ActMsgDto msgDto) {
        Result result = new Result();
        ActMsg msg = new ActMsg();
        BeanUtils.copyProperties(msgDto, msg);
        msg.setDelFlag(0);
        msg.setVersion(1);
        boolean b = msgService.save(msg);
        if (b) {
            result.setSuccess(true);
            result.setMessage("发送成功");

        } else {
            result.setSuccess(false);
            result.setCode(1);
        }
        return result;
    }

    @ApiOperation(value = "统计", notes = "统计")
    @ApiImplicitParam(name = "actId", value = "活动id", required = true)
    @GetMapping("statistics")
    public Result statistics(String actId) {
        Result<List<Map<String, Object>>> result = new Result<>();
        List<Map<String, Object>> mapList = shareService.countByActId(actId);
        result.setResult(mapList);
        return result;
    }

    private String getToken() {
        //授权（必填）
        String grant_type = "client_credential";
        //URL
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?";
        String params = "appid=" + Const.MINAPPID + "&secret=" + Const.MINSECRET + "&grant_type=" + grant_type;
        //发送请求
        JSONObject data = NetUtil.get(requestUrl + params);
        return data.getString("access_token");
    }

    //生成二维码 -> 返回地址url
    @ApiOperation(value = "获取二维码地址", notes = "获取二维码地址")
    @PostMapping("createQR")
    public Result createQR(@RequestBody ActQr actQr) {
        Result result = new Result();
        //切记加上"data:image/png;base64,不然会报错"
        String base = NetUtil.imgBase64(getToken(), actQr.getPath(), actQr.getWidth(), actQr.getScene(), 1);
        if (null == base) {
            result.setMessage("请求失败");
            result.setCode(1);
            return result;
        }
//            String path = "d://profile//";
        String path = "/files/";
        //将base64文件转为MultipartFile
        MultipartFile file1 = BASE64DecodedMultipartFile.base64ToMultipart(base);
        if (file1 == null) {
            result.setCode(1);
            result.setMessage("上传失败");
            return result;
        }
        //服务器地址
        return UploadUtil.upload(file1, path);
    }

}
